﻿using EasyNet.Componets.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace EasyNet.Componets.Core.Serialization
{
    public class EasyNetHttpQueryStringSerialization : IHttpQueryStringSerialization
    {
        #region 序列化

        public string Serialize(object obj)
        {
            if (obj == null) return string.Empty;
            StringBuilder sb = new StringBuilder();
            foreach (PropertyInfo property in obj.GetType().GetProperties())
            {
                if (property.PropertyType.IsValueType
                    || property.PropertyType == typeof(string)
                    || property.PropertyType == typeof(System.Guid))
                {
                    var value = property.GetValue(obj, null) ?? "";
                    sb.AppendFormat("{0}={1}&", property.Name, value);
                }

            }
            if(sb.Length > 0)
            {
                sb = sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();

        }

        #endregion

        #region 反序列化
        public T Deserialize<T>(string value) where T : new()
        {
            if (string.IsNullOrEmpty(value)) return default(T);
            var model = new T();

            var type = typeof(T);
            var dic = value.ToDictionaryFromFormRequest(true);
            foreach (PropertyInfo property in type.GetProperties())
            {
                if (!dic.ContainsKey(property.Name.ToLower()))
                {
                    continue;
                }
                var propertyValue = dic[property.Name.ToLower()];
                if (string.IsNullOrEmpty(propertyValue))
                {
                    continue;
                }
                if (property.PropertyType.IsValueType
                  || property.PropertyType == typeof(string))
                {
                    property.SetValue(model, Convert.ChangeType(propertyValue, property.PropertyType), null);
                }
                else if (property.PropertyType == typeof(System.Guid))
                {
                    property.SetValue(model, new Guid(propertyValue), null);
                }
            }

            return model;
        }

        #endregion


    }
}
